﻿using System;
using System.Data;
using System.Linq;
using System.Text;
using System.Transactions;
using System.ComponentModel;
using System.Collections.Generic;
using Kingdee.BOS;
using Kingdee.BOS.Util;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Orm;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Orm.Metadata.DataEntity;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.Interaction;
using Kingdee.K3.Core.SCM;
using CMK.K3.RI.STORE.Contract;


namespace KingdeeWebServiceProject
{
    public static class CreateBOSBillService
    {
        public static IOperationResult CreateCloudBosBill(Context ctx, BusinessInfo billInfo, DynamicObject dataBill, string strBillName, out string strBillNo, string sqlExcute = "", bool bAudit = true)
        {
            strBillNo = "";
            IOperationResult opResult = new OperationResult();

            OperateOption option = null;
            Dictionary<string, RespondDataContext> dictInteract;
            IDBService service = Kingdee.BOS.App.ServiceHelper.GetService<IDBService>();
            IMetaDataService metaService = Kingdee.BOS.Contracts.ServiceFactory.GetMetaDataService(ctx);
            ISaveService saveService = Kingdee.BOS.Contracts.ServiceFactory.GetSaveService(ctx);
            ISubmitService submitSvr = Kingdee.BOS.Contracts.ServiceFactory.GetSubmitService(ctx);
            ISetStatusService setStatusService = Kingdee.BOS.Contracts.ServiceFactory.GetSetStatusService(ctx);

            //using (KDTransactionScope scope = new KDTransactionScope(TransactionScopeOption.Required))
            //{
                //保存
                option = OperateOption.Create();
                OperateOptionUtils.SetIgnoreWarning(option, true);
                dictInteract = new Dictionary<string, RespondDataContext>();
                dictInteract.Add(SCMConst.MinusCheckSensor, null);
                OperateOptionExt.SetInteractionFlag(option, dictInteract);
                opResult = saveService.Save(ctx, billInfo, new DynamicObject[] { dataBill }, null, "Save");
                if (!opResult.IsSuccess)
                {
                    opResult.OperateResult.Add(new OperateResult()
                    {
                        MessageType = MessageType.Warning,
                        Message = string.Format("{0}保存失败，原因是：{1}", strBillName, GetFailMassage(opResult)),
                        Name = "保存失败",
                        SuccessStatus = false,
                    });

                    return opResult;
                }

                strBillNo = Convert.ToString(opResult.SuccessDataEnity.First()["BillNo"]);
            if ("第三方消费记录单".Equals(strBillName)) {
                opResult.OperateResult.Add(new OperateResult()
                {
                    MessageType = MessageType.Warning,
                    Message = string.Format("{0}保存成功", strBillName, GetFailMassage(opResult)),
                    Name = "保存成功",
                    SuccessStatus = true,
                });

                return opResult;

            }

                if (bAudit)
                {
                    //提交
                    var saveSucclst = opResult.SuccessDataEnity.Select(o => o["Id"]).Distinct().ToArray();
                    opResult = submitSvr.Submit(ctx, billInfo, saveSucclst, "Submit", option);
                    if (!opResult.IsSuccess)
                    {
                        opResult.OperateResult.Add(new OperateResult()
                        {
                            MessageType = MessageType.Warning,
                            Message = string.Format("{0}提交失败，原因是：{1}", strBillName, GetFailMassage(opResult)),
                            Name = "提交失败",
                            SuccessStatus = false,
                        });

                        return opResult;
                    }

                    //审核
                    option = OperateOption.Create();
                    OperateOptionUtils.SetIgnoreWarning(option, true);
                    dictInteract = new Dictionary<string, RespondDataContext>();
                    dictInteract.Add(SCMConst.MinusCheckSensor, null);
                    OperateOptionExt.SetInteractionFlag(option, dictInteract);
                    var submSucclst = opResult.SuccessDataEnity.Select(o => o["Id"]).Distinct().ToArray();
                    var lstAuditPK = submSucclst.Select(o => new KeyValuePair<object, object>(o, 0)).ToList();
                    opResult = setStatusService.SetBillStatus(ctx, billInfo, lstAuditPK, new List<object>() { "1", "" }, "Audit", option);
                    if (!opResult.IsSuccess)
                    {
                        opResult.OperateResult.Add(new OperateResult()
                        {
                            MessageType = MessageType.Warning,
                            Message = string.Format("{0}审核失败，原因是：{1}", strBillName, GetFailMassage(opResult)),
                            Name = "审核失败",
                            SuccessStatus = false,
                        });

                        return opResult;
                    }
                }

                if (!string.IsNullOrWhiteSpace(sqlExcute))
                {
                    DBUtils.Execute(ctx, sqlExcute);
                }

                //scope.Complete();

                return opResult;
            //}
        }

        private static string GetFailMassage(IOperationResult opResult)
        {
            string strErrMsg = string.Empty;
            StringBuilder sbMsg = new StringBuilder();

            if (opResult.InteractionContext != null)
            {
                try
                {
                    //Form提示消息
                    if (string.IsNullOrWhiteSpace(opResult.InteractionContext.SimpleMessage))
                        sbMsg.Append(opResult.InteractionContext.Option.GetVariableValue<string>("_FormTitle_"));
                    else
                        sbMsg.Append(opResult.InteractionContext.SimpleMessage);
                }
                catch
                {

                }

                try
                {
                    //显示器消息
                    if (opResult.InteractionContext.K3DisplayerModel != null)
                    {
                        K3DisplayerMessage[] lstMessage = opResult.InteractionContext.K3DisplayerModel.Messages;
                        if (lstMessage != null && lstMessage.Count() > 0)
                        {
                            foreach (var Message in lstMessage)
                            {
                                if (sbMsg.Length == 0)
                                {
                                    sbMsg.Append(Convert.ToString(Message.DataEntity[1]));
                                }
                                else
                                {
                                    sbMsg.AppendFormat("，{0}", Convert.ToString(Message.DataEntity[1]));
                                }
                            }
                        }
                    }
                }
                catch
                {

                }
            }

            if (opResult.OperateResult != null && opResult.OperateResult.Count > 0)
            {
                strErrMsg = string.Join("\r\n", opResult.OperateResult.Select(p => p.Message));
            }

            if (opResult.ValidationErrors != null && opResult.ValidationErrors.Count > 0)
            {
                strErrMsg = string.Join("\r\n", opResult.ValidationErrors.Select(p => p.Message));
            }

            if (sbMsg.Length == 0)
            {
                sbMsg.Append(strErrMsg);
            }
            else
            {
                sbMsg.AppendFormat("，{0}", strErrMsg);
            }

            return sbMsg.ToString();
        }
    }
}
